package com.yaolisheng.poetryandode.controller;

import com.yaolisheng.poetryandode.entity.IUser;
import com.yaolisheng.poetryandode.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * @Author yls
 * @Date 2021/6/2 11:29
 * @Version 1.0
 */
@Controller
public class LoginController {

    @Autowired
    private IUserService userService;

    @RequestMapping("/")
    public String toLogin() {
        return "login";
    }

    /**
     * 登录校验
     *
     * @param user
     * @param model
     * @param session
     * @return
     */
    @RequestMapping("/login")
    public String login(IUser user, Model model, HttpSession session) {
        List<IUser> iUsers = userService.queryAll(user);
        if (iUsers.size() < 1 || user == null) {
            model.addAttribute("msg", "登录失败，请检查用户名或密码");
            return "login";
        }
        session.setAttribute("sessionUser", iUsers.get(0));
        session.setMaxInactiveInterval(10 * 60);
        model.addAttribute("nickName", iUsers.get(0).getNickName());
        //请求重定向
        return "redirect:index/index";
    }

    /**
     * 转到注册页
     *
     * @return
     */
    @RequestMapping("/toRegister")
    public String toRegister() {
        return "register";
    }

    /**
     * 注册
     *
     * @param user
     * @param model
     * @return
     */
    @RequestMapping("/register")
    public String register(IUser user, Model model) {
        String userName = user.getUserName();
        String password = user.getPassword();
        if (userName == null || password == null) {
            model.addAttribute("msg", "用户名或密码不能为空");
            return "register";
        }
        IUser iUser = new IUser();
        iUser.setUserName(user.getUserName());
        List<IUser> iUsers = userService.queryAll(iUser);
        if (iUsers.size() > 0) {
            model.addAttribute("msg", "当前账号已被注册");
            return "register";
        }
        try {
            userService.insert(user);
            model.addAttribute("msg", "注册成功，请登录");
        } catch (Exception e) {
            System.out.println(e.getStackTrace());
        }
        return "login";
    }


}
